import { _decorator, Component, Node, Button, ToggleContainer, ScrollView, Label, Prefab, Color, instantiate, UITransform, Toggle, tween, Sprite, Vec2 } from 'cc';
import { PlayerType, EntityType, UnitType, BuildingType } from 'db://assets/battle/Enums';
import { UnitModel, BuildingModel } from 'db://assets/battle/Model';
import { PlayerStats } from './PlayerStats';
import { EntityStatsItem, IEntityData } from './EntityStatsItem';
import { LOG } from '../../../ConsoleLogCtrl';
const { ccclass, property } = _decorator;

/**
 * 实体信息项控制器
 * 用于控制entityInfoItem预制体中的节点显示和隐藏
 */
@ccclass('EntityInfoItemController')
export class EntityInfoItemController extends Component {

    /** 信息节点 - 点击触发显示/隐藏 */
    @property(Node)
    public infoNode: Node = null;

    /** 滚动视图节点 */
    @property(ScrollView)
    public scrollView: ScrollView = null;

    /** 切换容器节点 */
    @property(ToggleContainer)
    public toggleContainer: ToggleContainer = null;

    @property(Prefab)
    public itemPrefab: Prefab = null;

    /** 当前显示状态 */
    private isExpanded: boolean = true;

    /** 信息节点 - 点击触发显示/隐藏 */
    private infoLabel: Label = null;

    private playerStats: PlayerStats = null;
    private playerType: PlayerType = null;

    /** item节点缓存 */
    private itemNodes: Node[] = [];

    /** ScrollView的content节点 */
    private contentNode: Node = null;

    /** 当前显示的实体类型 */
    private currentEntityType: EntityType = EntityType.unit;

    /**
     * 组件初始化
     */
    protected onLoad(): void {
        this.initializeComponents();
        this.setupEvents();
    }

    /**
     * 初始化子组件
     */
    private initializeComponents(): void {
        // 如果没有通过属性设置，尝试通过名称查找子节点
        if (!this.infoNode) {
            this.infoNode = this.node.getChildByName('infoNode');
        }

        if (!this.scrollView) {
            this.scrollView = this.node.getChildByName('scrollView').getComponent(ScrollView);
        }

        if (!this.toggleContainer) {
            this.toggleContainer = this.node.getChildByName('unitOrBuilding').getComponent(ToggleContainer);
        }

        this.infoLabel = this.infoNode.getChildByName('info').getComponent(Label);

        // 获取ScrollView的content节点
        if (this.scrollView) {
            this.contentNode = this.scrollView.content;
        }

        this.toggleContainer.node.active = false; // 默认隐藏ToggleContainer
        this.scrollView.node.active = false; // 默认隐藏ScrollView

        // 设置Toggle事件监听
        this.setupToggleEvents();
    }

    /**
     * 初始化数据
    */
    public initData(playerStats: PlayerStats){
        this.playerStats = playerStats;
        this.playerType = playerStats.getPlayerType();
        // 更新显示状态
        this.updateDisplay();
    }


    /**
     * 设置事件监听
     */
    private setupEvents(): void {
        if (this.infoNode) {
            // 检查infoNode是否有Button组件
            const button = this.infoNode.getComponent(Button);
            if (button) {
                // 如果有Button组件，监听按钮点击事件
                button.node.on(Button.EventType.CLICK, this.onInfoNodeClick, this);
            } else {
                // 如果没有Button组件，监听节点的触摸事件
                this.infoNode.on(Node.EventType.TOUCH_END, this.onInfoNodeClick, this);
            }
        }
    }

    /**
     * 设置Toggle事件监听
     */
    private setupToggleEvents(): void {
        if (this.toggleContainer) {
            let togs = this.toggleContainer.toggleItems;
            togs.forEach(tog => {
                tog.node.on(Toggle.EventType.TOGGLE, (toggle: Toggle) => {
                    // 处理标签切换事件
                    this.handleToggleSwitch(toggle.node.name);
                }, this);
            })
        }
    }

    /**
     * infoNode点击事件处理
     */
    private onInfoNodeClick(): void {
        this.toggleDisplay();
    }

    /**
     * 切换显示状态
     */
    public toggleDisplay(): void {
        this.isExpanded = !this.isExpanded;
        this.updateDisplay();
    }

    /**
     * 显示ScrollView和ToggleContainer
     */
    public showContent(): void {
        this.isExpanded = true;
        this.updateDisplay();
    }

    /**
     * 隐藏ScrollView和ToggleContainer
     */
    public hideContent(): void {
        this.isExpanded = false;
        this.updateDisplay();
    }

    /**
     * 更新显示状态
     */
    private updateDisplay(): void {
        this.setTileText(this.playerStats);
        if (this.scrollView) {
            this.scrollView.node.active = this.isExpanded;
        }

        if (this.toggleContainer) {
            this.toggleContainer.node.active = this.isExpanded;
        }

        // 更新item显示
        this.updateItemDisplay();

    }

    /**
     * 设置显示状态
     * @param expanded 是否展开
     */
    public setExpanded(expanded: boolean): void {
        this.isExpanded = expanded;
        this.updateDisplay();
    }

    /**
     * 获取当前显示状态
     * @returns 当前是否展开
     */
    public getExpanded(): boolean {
        return this.isExpanded;
    }

    /**
     * 显示玩家实体统计数据
    */
    public getPlayerType(): PlayerType {
        return this.playerType;
    }

    /**
     * 获取颜色
     */
   private getColorByPlayerType(): Color {
        const playerType = this.playerStats.getPlayerType();
        switch (playerType) {
            case PlayerType.PLAYER1:
                return new Color(255, 0, 0, 255); // 红色
            case PlayerType.PLAYER2:
                return new Color(0, 100, 255, 255); // 蓝色
            default:
                return new Color(255, 255, 0, 255); // 默认黄色
        }
   }

   /**
    * 设置文本显示
   */
    public setTileText(playerStats: PlayerStats): void {
        if (this.infoLabel && playerStats) {
            const units = playerStats.getAllUnits();
            const buildings = playerStats.getAllBuildings();
            const playerType = playerStats.getPlayerType();
            this.infoLabel.color = this.getColorByPlayerType();
            this.infoLabel.string =  `玩家: ${playerStats.getId()}  单位:${units.length}  建筑:${buildings.length}`;
        }
    }

    /**
     * 更新数据
     * @param playerStats 新的玩家统计数据
     */
    public updateData(playerStats: PlayerStats): void {
        if (!playerStats) {
            LOG.warn('EntityInfoItemController: updateData received null playerStats');
            return;
        }

        // 更新数据引用
        this.playerStats = playerStats;
        this.playerType = playerStats.getPlayerType();

        // 刷新显示
        this.updateDisplay();
    }

    /**
     * 处理Toggle切换事件
     * @param toggleType Toggle类型
     * @param isChecked 是否选中
     */
    private handleToggleSwitch(toggleType: string) {

        switch(toggleType){
            case "unitToggle":
                this.currentEntityType = EntityType.unit;
                break;
            case "buildingToggle":
                this.currentEntityType = EntityType.building;
                break;
            default:
                LOG.warn(`未知的Toggle类型: ${toggleType}`);
                break;
        }
        // 更新item显示
        this.updateItemDisplay();
    }

    /**
     * 更新item显示
     */
    private updateItemDisplay(): void {
        if (!this.playerStats || !this.contentNode) {
            return;
        }

        // 获取当前需要显示的实体数据
        let entities: (UnitModel | BuildingModel)[] = [];

        if (this.currentEntityType === EntityType.unit) {
            entities = this.playerStats.getAllUnits();
        } else if (this.currentEntityType === EntityType.building) {
            entities = this.playerStats.getAllBuildings();
        }
        let playerType = this.playerStats.getPlayerType();

        // 确保有足够的item节点
        this.ensureItemNodes(entities.length);

        // 更新每个item的数据和显示状态
        for (let i = 0; i < this.itemNodes.length; i++) {
            const itemNode = this.itemNodes[i];

            if (i < entities.length) {
                // 显示item并更新数据
                itemNode.active = true;
                this.updateItemData(itemNode, entities[i], this.currentEntityType, playerType);
            } else {
                // 隐藏多余的item
                itemNode.active = false;
            }
        }
    }

    /**
     * 确保有足够的item节点
     * @param requiredCount 需要的节点数量
     */
    private ensureItemNodes(requiredCount: number): void {
        // 如果现有节点不够，创建新的
        while (this.itemNodes.length < requiredCount) {
            const newItem = this.createItemNode();
            if (newItem) {
                this.itemNodes.push(newItem);
            } else {
                break; // 如果创建失败，停止创建
            }
        }
    }

    /**
     * 创建item节点
     * @returns 创建的item节点
     */
    private createItemNode(): Node {
        if (!this.contentNode) {
            LOG.warn('EntityInfoItemController: contentNode is null');
            return null;
        }

        let itemNode: Node = null;

        if (this.itemPrefab) {
            // 使用预制体创建item
            itemNode = instantiate(this.itemPrefab);
        } else {
            // 创建默认的item节点
            itemNode = new Node('EntityStatsItem');
            itemNode.addComponent(EntityStatsItem);

            // 设置默认大小
            const transform = itemNode.getComponent(UITransform) || itemNode.addComponent(UITransform);
            transform.width = 600;
            transform.height = 120;
        }

        // 添加到content节点
        itemNode.parent = this.contentNode;

        return itemNode;
    }

    /**
     * 更新item节点的数据
     * @param itemNode item节点
     * @param entityModel 实体模型数据
     * @param entityType 实体类型
     * @param playerType 玩家类型
     */
    private updateItemData(itemNode: Node, entityModel: UnitModel | BuildingModel, entityType: EntityType, playerType: PlayerType): void {

        const entityStatsItem = itemNode.getComponent(EntityStatsItem);
        if (!entityStatsItem) {
            LOG.warn('EntityInfoItemController: EntityStatsItem component not found');
            return;
        }

        // 创建实体数据
        let entityData: IEntityData;

        if (entityType === EntityType.unit) {
            const unitModel = entityModel as UnitModel;
            entityData = EntityStatsItem.createFromUnitModel(playerType, unitModel);
        } else if (entityType === EntityType.building) {
            const buildingModel = entityModel as BuildingModel;
            entityData = EntityStatsItem.createFromBuildingModel(playerType, buildingModel);
        } else {
            LOG.warn('EntityInfoItemController: Unsupported entity type:', entityType);
            return;
        }

        // 设置实体数据
        entityStatsItem.setEntityData(entityData);
    }

    /**
     * 清理所有item节点
     */
    private clearAllItems(): void {
        this.itemNodes.forEach(item => {
            if (item && item.isValid) {
                item.destroy();
            }
        });
        this.itemNodes = [];
    }

    /**
     * 设置当前显示的实体类型
     * @param entityType 实体类型
     */
    public setCurrentEntityType(entityType: EntityType): void {
        this.currentEntityType = entityType;
        this.updateItemDisplay();
    }

    /**
     * 获取当前显示的实体类型
     * @returns 当前实体类型
     */
    public getCurrentEntityType(): EntityType {
        return this.currentEntityType;
    }

    /**
     * 组件销毁时清理
     */
    protected onDestroy(): void {
        // 清理所有item节点
        this.clearAllItems();

        // 移除事件监听
        if (this.infoNode) {
            const button = this.infoNode.getComponent(Button);
            if (button) {
                button.node.off(Button.EventType.CLICK, this.onInfoNodeClick, this);
            } else {
                this.infoNode.off(Node.EventType.TOUCH_END, this.onInfoNodeClick, this);
            }
        }
    }

        /**
     * 滚动到指定的EntityStatsItem
     * @param itemNode 要滚动到的节点
     */
    public scrollToEntityStatsItem(entityId: number): void {
        if (!this.scrollView || !entityId) return;

        // 计算目标节点在ScrollView中的位置
        const itemNode = this.itemNodes.find(item => item.getComponent(EntityStatsItem).getEntityData().id === entityId);
        const worldPos = itemNode.getWorldPosition();
        const localPos = this.scrollView.node.getComponent(UITransform).convertToNodeSpaceAR(worldPos);

        // 计算滚动位置
        const scrollContent = this.scrollView.content;
        const contentHeight = scrollContent.getComponent(UITransform).height;
        const viewHeight = this.scrollView.node.getComponent(UITransform).height;

        // 计算目标位置的归一化值（0-1）
        let normalizedPos = (localPos.y + contentHeight / 2) / contentHeight;
        normalizedPos = Math.max(0, Math.min(1, normalizedPos));

        // 设置滚动位置
        this.scrollView.scrollTo(new Vec2(0, normalizedPos), 0.5);
    }

    /**
     * 高亮显示EntityStatsItem
     * @param entityId 实体ID
     */
    public highlightEntityStatsItemNode(entityId: number): void {
        if (!entityId) return;

        // 查找对应的item节点
        const itemNode = this.itemNodes.find(item => {
            const entityStatsItem = item.getComponent(EntityStatsItem);
            return entityStatsItem && entityStatsItem.getEntityData().id === entityId;
        });

        if (!itemNode) return;

        // 获取Sprite组件
        const spriteComponent = itemNode.getComponent(Sprite);
        if (!spriteComponent) return;

        // 创建高亮颜色（更亮的黄色）
        const highlightColor = new Color(255, 255, 0, 255);

        // 停止之前可能存在的动画
        //tween(spriteComponent).stop();


        // 创建颜色变化动画：原色 -> 高亮色 -> 原色，持续2秒
        tween(spriteComponent)
            .to(0.3, { color: highlightColor }) // 0.3秒变为高亮色
            .to(1.4, { color: highlightColor }) // 保持高亮1.4秒
            .to(0.3, { color: Color.WHITE })  // 0.3秒恢复原色
            .start();
    }
}